import snap7
from snap7.util import get_real

def plc_connect(ip, type, rack=0, slot=1):
    """
    连接初始化
    :param ip: PLC的IP地址
    :param type: 连接类型，1 for PG, 2 for OP, 3 to 10 for S7 Basic
    :param rack: 通常为0
    :param slot: 根据plc安装，一般为0或1
    :return: client对象
    """
    client = snap7.client.Client()
    client.set_connection_type(type)
    client.connect(ip, rack, slot)
    return client


def plc_con_close(client):
    """
    连接关闭
    :param client: client对象
    """
    client.disconnect()


def read_VB(client, offset):
    """
    读取VB区数据
    :param client: client对象
    :param offset: 起始偏移量
    :return: 读取的数据
    """
    vb_data = client.db_read(1, offset, 4)
    # return vb_data[0]
    float_value = get_real(vb_data, 0)
    return float_value

if __name__ == "__main__":
    client_fd = plc_connect('192.168.0.12', 2)  # 假设PLC的IP地址为192.168.2.1
    print("connect success")
    data = read_VB(client_fd, 228)  # 假设读取VB1的数据
    print(data)
    plc_con_close(client_fd)
